<?php
// +----------------------------------------------------------------------
// | WoShiMaiJia Projcet
// +----------------------------------------------------------------------
// | Copyright (c) 2010 http://www.woshimaijia.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: xinqiyang <517577550@qq.com>
// +----------------------------------------------------------------------
/**
 * 数据库内容替换
 * @author xinqiyang
 * @date   2010-5-26
 *
 */
class ReplaceAction extends Action {
	/**
	 *
	 */
	function index()
	{

		$this->display();
	}

	/**
	 * 手动替换
	 */
	private function replacewords()
	{
		$field = $_REQUEST['field'];
		$table = C('DB_PREFIX').$_REQUEST['table'];
		$word = $_REQUEST['words'];
		$toword = $_REQUEST['towords'];
		//替换词语
		$result = $d->execute("Update $table set $filed=Replace($field,'$word','$toword')");
			
		if($result)
		{
			return 'replace ok';
		}

	}

	/**
	 * 加载词库自动替换
	 */
	private function autoreplace()
	{
	 //参数
		$table = C('DB_PREFIX').$_REQUEST['table'];
		$field = $_REQUEST['field'];
		$count = (int)$_REQUEST['count'];//替换的词组数目    10 个  20个

		//返回信息
		$returnmsg = '';
		//初始化替换计数
		$replacecount = 0;
		//加载词库
		$d = M('wordstock');
		//随即排序词库
		$words = $d->order('RAND()')->select();
		foreach($words as $value)
		{
			//被替换的词
			$keywords = $value['keywords'];
			$arr = explode(',',$value['replacewords']);
			$randkey =array_rand($arr,1);
			//得到替换的词
			if($arr[$randkey])
			{
				$replace = $arr[$randkey];
			}
			if($replacecount < $count)
			{
				//替换词语
				$result = $d->execute("Update $table set $filed=Replace($field,'$keywords','$replace')");
			}

			if($result)
			{
				$replacecount ++; //叠加个数
				$returnmsg .= $replace.',';
			}
		}
		return $returnmsg;
	}

	/**
	 * 替换成TAG
	 * 可以修改拼接的字符串
	 */
	private function replacetag()
	{
		//替换的TAG 格式为   我们,你们,他们  以逗号隔开
		$tagwords = $_REQUEST['tagwords'];
		//拆分tag字符串
		$tagarr = explode(',',$tagwords);
		$return ="";
		//构造语句进行替换,先替换TAG
		if(is_array($tagarr))
		{
			//替换为TAG
			foreach($tagarr as $tag)
			{
				$tags = "<a href='__APP__/tags/words/$tag' class='wunlink' target='_blank'>$tag</a>";
				//替换数据库
				$result = $d->execute("Update $table set $filed=Replace($field,'$tag','$tags')");
				if($result)
				{
					$return.=$tag;
				}
			}
			//返回替换成功的这些TAG
			return $return;
		}
	}

	/**
	 * 更新词库方法
	 *
	 * 添加关键字
	 *
	 * 搜索关键字,添加替换的关键词
	 */
	function updatewords()
	{

		$this->display();
	}
	
	function savewords()
	{
		$d = M('wordstock');
		if($d->create())
		{
			$result = $d->save();
			if($result)
			{
				$this->ajaxReturn('save OK');
			}
		}
	}
}


?>